<%@ page language="java" import="com.alibaba.fastjson.JSONArray" pageEncoding="UTF-8" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="weaver.alioss.AliOSSObjectManager" %>
<%@ page import="weaver.conn.ConnStatement" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.file.AESCoder" %>
<%@ page import="weaver.file.FileManage" %>
<%@ page import="weaver.file.FileUpload" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="weaver.sm.SM4Utils" %>
<%@ page import="weaver.system.SystemComInfo" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.UUID" %>
<%@ page import="java.util.concurrent.CountDownLatch" %>
<%@ page import="java.util.concurrent.ExecutorService" %>
<%@ page import="java.util.concurrent.Executors" %>
<%@ page import="java.util.zip.ZipEntry" %>
<%@ page import="java.util.zip.ZipInputStream" %>
<%@ page import="java.util.zip.ZipOutputStream" %>
<%--获取流水号--%>
<%
    ExecutorService pool = Executors.newFixedThreadPool(20);
    JSONArray dataList = getImagefileInfo();
    int tasks = dataList.size();
    CountDownLatch waitBefore = new CountDownLatch(tasks);
    CountDownLatch afterBefore = new CountDownLatch(tasks);
    out.print(">>>>>tasks=" + tasks + "<br/>");
    long now = System.currentTimeMillis();
    for (int i = 0; i < dataList.size(); i++) {
        final int index = i;
        pool.execute(() -> {
            try {
                waitBefore.await();
                String static_fileRealPath = dataList.getJSONObject(index).getString("static_fileRealPath");
                String static_isZip = dataList.getJSONObject(index).getString("static_isZip");
                String static_tokenKey = dataList.getJSONObject(index).getString("static_tokenKey");
                String static_storageStatus = dataList.getJSONObject(index).getString("static_storageStatus");
                String imagefilename = dataList.getJSONObject(index).getString("imagefilename");
                String imagefileid = dataList.getJSONObject(index).getString("imagefileid");
                handleTask(static_tokenKey, static_storageStatus, static_fileRealPath, static_isZip, imagefileid, imagefilename);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                afterBefore.countDown();
            }
        });
        waitBefore.countDown();
    }
    out.print(tasks + "个任务执行完的总耗时:" + (System.currentTimeMillis() - now) + "毫秒<br/>");
%>
<%!
    public static BaseBean baseBean = new BaseBean();

    public JSONArray getImagefileInfo() {
        RecordSet rs = new RecordSet();
        JSONArray dataList = new JSONArray();
        String sql = "select imagefileid,imagefilename,fileRealPath,imageFileType,isZip,isaesencrypt,aescode,tokenKey,storageStatus  from ImageFile where isaesencrypt = 0";
        rs.executeQuery(sql);
        int counts = rs.getCounts();
        baseBean.writeLog(">>>>>getImagefileInfo>>>>>counts=" + counts);
        while (rs.next()) {
            JSONObject dataJson = new JSONObject();
            String static_fileRealPath = Util.null2String(rs.getString("fileRealPath"));
            String static_isZip = Util.null2String(rs.getString("isZip"));
            String static_tokenKey = Util.null2String(rs.getString("tokenKey"));
            String static_storageStatus = Util.null2String(rs.getString("storageStatus"));
            String imagefilename = Util.null2String(rs.getString("imagefilename"));
            String imagefileid = Util.null2String(rs.getString("imagefileid"));
            dataJson.put("static_fileRealPath", static_fileRealPath);
            dataJson.put("static_isZip", static_isZip);
            dataJson.put("static_tokenKey", static_tokenKey);
            dataJson.put("static_storageStatus", static_storageStatus);
            dataJson.put("imagefilename", imagefilename);
            dataJson.put("imagefileid", imagefileid);
            dataList.add(dataJson);
        }
        baseBean.writeLog(">>>>>getImagefileInfo>>>>>dataList=" + dataList.size());
        return dataList;
    }

    public void handleTask(String static_tokenKey, String static_storageStatus, String static_fileRealPath, String static_isZip, String imagefileid, String imagefilename) {
        InputStream imagefile = null;
        try {
            baseBean.writeLog(">>>>>handleTask>>>>>imagefileid=" + imagefileid);
            baseBean.writeLog(">>>>>handleTask>>>>>imagefilename=" + imagefilename);
            boolean isonlyAliOSS = false;
            if (!static_tokenKey.equals("") && static_storageStatus.equals("1") && AliOSSObjectManager.isonlyAliOSS()) {
                isonlyAliOSS = true;
            }
            if (isonlyAliOSS) {
                imagefile = weaver.alioss.AliOSSObjectUtil.downloadFile(static_tokenKey);
            } else {
                if (static_fileRealPath != null && !static_fileRealPath.equals("")) {
                    File thefile = new File(static_fileRealPath);
                    if (static_isZip.equals("1")) {
                        ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile));
                        if (zin.getNextEntry() != null) {
                            imagefile = new BufferedInputStream(zin);
                        }
                    } else {
                        imagefile = new BufferedInputStream(new FileInputStream(thefile));
                    }
                } else {
                    ConnStatement statement = null;
                    try {
                        statement = new ConnStatement();
                        boolean isoracle = ("oracle").equals(statement.getDBType());
                        statement.setStatementSql("select imagefile from ImageFile where imagefileid = " + imagefileid);
                        statement.executeQuery();
                        if (statement.next()) {
                            if (isoracle) {
                                imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile"));
                            } else {
                                imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile"));
                            }
                        }
                    } catch (Exception ex) {
                    } finally {
                        try {
                            if (statement != null) {
                                statement.close();
                            }
                        } catch (Exception ex) {
                        }
                    }
                }
            }
            //正文的处理
            ByteArrayOutputStream bout = null;
            int byteread;
            byte data[] = new byte[1024];
            try {
                bout = new ByteArrayOutputStream();
                while ((byteread = imagefile.read(data)) != -1) {
                    bout.write(data, 0, byteread);
                    bout.flush();
                }
                byte[] fileBody = bout.toByteArray();
                JSONObject resultJson = saveImageFile(imagefilename, fileBody);
                String fileRealPath = resultJson.getString("fileRealPath");
                String aescode = resultJson.getString("aescode");
                baseBean.writeLog(">>>>>handleTask>>>>>resultJson=" + resultJson);
                baseBean.writeLog(">>>>>handleTask>>>>>fileRealPath=" + fileRealPath);
                baseBean.writeLog(">>>>>handleTask>>>>>aescode=" + aescode);
                // rs.executeUpdate("update ImageFile set fileRealPath=?,aescode=?,isaesencrypt=1 where imageFileId=?",fileRealPath,aescode,imagefileid);
            } catch (Exception e) {
                if (bout != null) {
                    bout.close();
                }
                new BaseBean().writeLog("ImageFileManager.getInputStreamById(int imageFileId_para),exception1:", e);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新建物理文件
     * @return 新的附件id
     */
    public JSONObject saveImageFile(String imageFileName, byte[] data) {
        JSONObject resultJson = new JSONObject();
        BaseBean baseBean = new BaseBean();
        String static_fileRealPath = "";
        try {
            String static_aescode = "";
            String static_imageFileName = imageFileName;
            String static_isZip = "1";
            int static_isaesencrypt = 1;
            SystemComInfo syscominfo = new SystemComInfo();
            String createdir = FileUpload.getCreateDir(syscominfo.getFilesystem());
            String random = UUID.randomUUID().toString(); // 解决高并发下，文件重复问题 李迎新
            String fileName = random;
            static_isaesencrypt = Util.getIntValue(syscominfo.getIsaesencrypt(), 0);
            static_aescode = Util.getRandomString(13);
            if ("1".equals(static_isZip)) {
                fileName += ".zip";
            }
            String fullName = createdir + fileName;
            static_fileRealPath = fullName;
            FileManage.createDir(createdir);
            //写压缩文件
            OutputStream fileOut = null;
            try {
                File file = new File(static_fileRealPath);
                if (static_isZip.equals("1")) {
                    ZipOutputStream filezipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
                    filezipOut.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
                    filezipOut.putNextEntry(new ZipEntry(random));
                    fileOut = filezipOut;
                } else {
                    fileOut = new BufferedOutputStream(new FileOutputStream(file));
                }

                if (static_isaesencrypt == 1) {
                    fileOut = AESCoder.encrypt(fileOut, static_aescode);
                    String sm4 = Util.null2String(baseBean.getPropValue("weaver_security_type", "reversible_enc_type"));
                    if ("sm4".equalsIgnoreCase(sm4) && static_aescode.startsWith("sm4start") && static_aescode.endsWith("sm4end")) {
                        SM4Utils sM4Utils = new SM4Utils();
                        byte[] _key = sM4Utils.getSMCode(static_aescode);
                        data = sM4Utils.encodeBytes(data, _key);
                    }
                }

                fileOut.write(data, 0, data.length);

            } catch (Exception ex) {
            } finally {
                fileOut.close();
            }
            AliOSSObjectManager aliOSSObjectManager = new AliOSSObjectManager();
            aliOSSObjectManager.uploadFile(static_fileRealPath, static_imageFileName, static_isZip, "" + static_isaesencrypt, static_aescode);
            resultJson.put("fileRealPath", static_fileRealPath);
            resultJson.put("aescode", static_aescode);
        } catch (Exception ex) {

        }
        return resultJson;
    }
%>